from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class ShouyePage:
    # 元素定位（用元组存储，便于维护）
    APP_LOGO = (By.XPATH, '//div[@class="app_logo"]')
    ADD_BACKPACK = (By.XPATH, '//*[@id="add-to-cart-sauce-labs-backpack"]')
    SHOPPING_CART = (By.XPATH, '//*[@id="shopping_cart_container"]/a')
    BACKPACK_NAME = (By.XPATH, '//*[@id="item_4_title_link"]/div')
    REMOVE_BUTTON = (By.XPATH, '//*[@id="remove-sauce-labs-backpack"]')
    CONTINUE_SHOPPING = (By.XPATH, '//*[@id="continue-shopping"]')

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)  # 显式等待实例

    # 页面操作封装
    def get_app_logo_text(self):
        """获取首页logo文本"""
        return self.wait.until(EC.visibility_of_element_located(self.APP_LOGO)).text

    def add_backpack_to_cart(self):
        """添加背包到购物车"""
        self.wait.until(EC.element_to_be_clickable(self.ADD_BACKPACK)).click()

    def go_to_shopping_cart(self):
        """进入购物车"""
        self.wait.until(EC.element_to_be_clickable(self.SHOPPING_CART)).click()

    def get_cart_backpack_name(self):
        """获取购物车中背包名称"""
        return self.wait.until(EC.visibility_of_element_located(self.BACKPACK_NAME)).text

    def remove_backpack(self):
        """从购物车移除背包"""
        self.wait.until(EC.element_to_be_clickable(self.REMOVE_BUTTON)).click()

    def is_backpack_in_cart(self):
        """判断背包是否在购物车中"""
        elements = self.driver.find_elements(*self.BACKPACK_NAME)
        return len(elements) > 0

    def continue_shopping(self):
        """点击继续购物"""
        self.wait.until(EC.element_to_be_clickable(self.CONTINUE_SHOPPING)).click()